//
//  SKXCallViewController.m
//  NewChat
//
//  Created by songKX on 16/3/10.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "SKXCallViewController.h"
#import "TBActivityView.h"
@interface SKXCallViewController ()<EMChatManagerDelegate,EMCallManagerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *userHeadView;

@property (weak, nonatomic) IBOutlet UILabel *userName;

@property (weak, nonatomic) IBOutlet UILabel *callStatus;
@property (weak, nonatomic) IBOutlet UILabel *netWorkStatus;
@property (nonatomic , assign) BOOL silence;
@property (nonatomic , assign) BOOL speakerType;
@property (weak, nonatomic) IBOutlet UIButton *hangUpDown;
@property (nonatomic , assign) BOOL hangStatus;
@property (nonatomic , assign) CGFloat brightNess;

@property (weak, nonatomic) IBOutlet UIButton *hangGreen;


@end

@implementation SKXCallViewController


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [[EaseMob sharedInstance].callManager removeDelegate:self];
    
    //关闭屏幕传感器
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
    //删除监听
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil];
    
    
    [[EaseMob sharedInstance].callManager asyncEndCall:_currentCall.sessionId reason:eCallReasonNull];
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    

    AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
    
    [userQuery includeKey:@"username"];
    
    [userQuery whereKey:@"username" equalTo:self.chater];
    
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        AVObject *obj = [objects lastObject];
    
        
        self.userName.text = obj[@"nickname"];
        
        self.userHeadView.image = [UIImage imageNamed:obj[@"userImageName"]];
        
    }];
    
    
    //打开距离传感器
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    //添加监控距离传感器的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(sensorStateChange:)
                                                 name:UIDeviceProximityStateDidChangeNotification
                                               object:nil];
    
    self.userName.text = self.chatPerson[@"nickname"];
    [GLobalRealReachability startNotifier];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChanged:) name:kRealReachabilityChangedNotification object:nil];
    
    
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    if (status == 1) {
        self.netWorkStatus.text = @"正在使用数据流量";
    }else if (status == 2){
        
        self.netWorkStatus.text = @"正在使用WIFI网络";
        
    }
    
    self.userHeadView.image = [UIImage imageNamed:self.chatPerson[@"userImageName"]];
   
    
    //添加代理
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    
    self.navigationController.navigationBar.translucent = YES;
    
    self.tabBarController.tabBar.translucent = YES;
    
    self.silence = NO;
    
    self.speakerType = NO;
    
    EMError * error = nil;
    
    if(self.chaterBudy){
        
        NSLog(@"次级面来的");
        
        self.hangGreen.hidden = YES;
       
        EMCallSession * currentSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:self.chaterBudy.username timeout:0 error:&error];
        
        NSLog(@"%@",self.chaterBudy.username);
        
        self.callStatus.text = @"正在等待通话.....";
        
        
        
        NSLog(@"%@",error);
        
        if (error) {
            
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"通话出错，检测网络" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            
            [self presentViewController:con animated:YES completion:nil];
            
            
        }
        
        self.currentCall = currentSession;

        
    }else{
        
        self.hangGreen.hidden = NO;
        
        NSLog(@"主界面来的");
        
        self.callStatus.text = @"正在响铃.....";
        
        self.hangUpDown.backgroundColor = nil;
        
        self.hangStatus = YES;
        
    }

    
    
    
    
    // Do any additional setup after loading the view from its nib.
}

//距离传感器响应
-(void)sensorStateChange:(NSNotificationCenter *)notification;
{
    if ([[UIDevice currentDevice] proximityState] == YES) {
        
        self.brightNess = [UIScreen mainScreen].brightness;
        
        NSLog(@"正在靠近");
        [[UIScreen mainScreen] setBrightness:0];
        
        
    }else{
        NSLog(@"已经远离");
        
        [[UIScreen mainScreen]setBrightness:self.brightNess];
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



//状体变化时

-(void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error{
    
    
    if (callSession.status ==eCallSessionStatusAccepted) {
        
        
        self.callStatus.text = @"正在通话.....";
        
        
    }
    //通话被结束的原因
    
    NSLog(@"问题的原因是%ld",reason);
    
    switch (reason) {
        case eCallReasonNull:{
            
            NSLog(@"正常结束");
            
            break;
        }
        case eCallReason_Busy:{
            
            NSLog(@"对方占线");
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                if(self.chaterBudy){
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }
                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"对方占线" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            
            [self presentViewController:con animated:YES completion:nil];

            
            break;
            
        }
        case eCallReason_Reject:{
            
            NSLog(@"对方拒绝");
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                if(self.chaterBudy){
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }

                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"对方拒绝" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            
            [self presentViewController:con animated:YES completion:nil];

            
            
            break;
            
        }
        case eCallReason_Hangup:{
            
            NSLog(@"对方挂断");
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                if(self.chaterBudy){
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }

                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"对方挂断" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            
            [self presentViewController:con animated:YES completion:nil];

            
            break;
            
        }
        case eCallReason_NoResponse:eCallReason_Offline:{
            
            NSLog(@"对方无响应或对方不在线");
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                if(self.chaterBudy){
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }

                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"对方无响应" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            
            [self presentViewController:con animated:YES completion:nil];

            
            break;
        }
        case eCallReason_Failure:{
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                if(self.chaterBudy){
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }

                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"通话失败" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            
            [self presentViewController:con animated:YES completion:nil];
            
            
            NSLog(@"通话失败");
            
        }
        default:
            NSLog(@"通话出错");
            
            break;
    }
}
//挂断电话

- (IBAction)hangUpCall:(id)sender {
    
        
    self.callStatus.text = @"通话结束";
        
    NSLog(@"挂电话");
    
    [[EaseMob sharedInstance].callManager asyncEndCall:_currentCall.sessionId reason:eCallReasonNull];

    if(self.chaterBudy){
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
    
}
//静音

- (IBAction)voiceOff:(UIButton *)sender {
    
    self.silence = !self.silence;
    
    [[EaseMob sharedInstance].callManager markCallSession:self.currentCall.sessionId asSilence:self.silence];
    
    if (self.silence) {
        sender.backgroundColor = [UIColor redColor];

    }else{
        
        sender.backgroundColor = nil;
        
    }
    
    
   
    
}
//改变扬声器
- (IBAction)changeVoice:(UIButton *)sender {
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if (sender.selected) {
        //听筒
        sender.backgroundColor = nil;
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
    }else {
        //扬声器
        sender.backgroundColor= [UIColor redColor];
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    }
    [audioSession setActive:YES error:nil];
    sender.selected = !sender.selected;

    
}


- (void)networkChanged:(NSNotification *)notification
{
    
    [GLobalRealReachability reachabilityWithBlock:^(ReachabilityStatus status) {
        
        NSString *statuStr = nil;
        switch (status)
        {
            case RealStatusNotReachable:
            {
                
                NSLog(@"没有网络连接");
                
                self.netWorkStatus.text = @"没有网络连接";
                
                
                
                break;
            }
                
            case RealStatusViaWWAN:
            {
                
                NSLog(@"正在使用数据流量");
                
                statuStr = @"正在使用数据流量";
                self.netWorkStatus.text = statuStr;
                
                break;
            }
                
            case RealStatusViaWiFi:
            {
                
                NSLog(@"正在使用WIFI");
                statuStr = @"正在使用WIFI";
                
                self.netWorkStatus.text = statuStr;

                break;
            }
            default:
                self.netWorkStatus.text = @"发生错误";

                
                break;
        }
        
        
    }];
}

- (IBAction)hangCallGreen:(UIButton *)sender {
    
    
    sender.hidden = YES;
    
    [[EaseMob sharedInstance].callManager asyncAnswerCall:self.currentCall.sessionId];
    
    
    
}


@end
